using Core.SimpleTemp.Application;
using Core.SimpleTemp.Common.Authorization;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Mvc.Api.Internal;
using Core.Toolkit.Authorization;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using System.Linq;

namespace Core.SimpleTemp.Api.Api
{
    /// <summary>
    /// CBS_ExamQuestions
    ///</summary>
    [ApiExplorerSettings(GroupName = "Sys")]//swagger分类标签
    [Route("api/[controller]")]//路由说明
    [EnableCors("any")]//跨域规则
    [ApiController]//APi标识Controller
    [Authorize]//验证是否登录
    public class CBS_ExamQuestionsController : CoreApiController
    {
        private readonly CBS_ExamQuestionsService _service;
        private readonly CBS_TotalCheckItemService _serviceItem;
        private readonly CBS_QuestionsService _questions;

        /// <summary>
        /// CBS_ExamQuestions
        ///</summary>
        public CBS_ExamQuestionsController(CBS_ExamQuestionsService service, CBS_TotalCheckItemService serviceItem, CBS_QuestionsService questions)
        {
            _service = service;
            _serviceItem = serviceItem;
            _questions = questions;
        }

        #region 基础增删改查
        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetList")]
        [PermissionFilter(nameof(CBS_ExamQuestionsController) + "_" + nameof(CBS_ExamQuestionsController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult>
            GetList(PagingModel<CBS_ExamQuestionsDto>
                pagingQueryModel)
        {
            IPageModel<CBS_ExamQuestionsDto>
                result;
            result = await _service.GetList(pagingQueryModel);
            return this.JsonSuccess(result);
        }

        /// <summary>
        /// 添加/修改
        ///</summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("Save")]
        [PermissionFilter(nameof(CBS_ExamQuestionsController) + "_" + nameof(CBS_ExamQuestionsController.SaveAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult>
            SaveAsync(CBS_ExamQuestionsDto dto)
        {
            //添加
            if (Equals(dto.Id, Guid.Empty))
            {
                dto.PaperUserId = UserIdentity.Id;
                string SysDepartmentID = await _serviceItem.GetDepartmentId(UserIdentity.Id.ToString());
                if (SysDepartmentID == null || SysDepartmentID == "") { }
                else
                {
                    dto.CreateDept = Guid.Parse(SysDepartmentID);
                }
                dto.CreateFactory = UserIdentity.Factory;
                //await _service.InsertAsync(dto);
                //return this.JsonSuccess(string.Empty);

                //判断
                PagingModel<CBS_QuestionsDto> pagingQueryModel1 = new PagingModel<CBS_QuestionsDto>();
                pagingQueryModel1.Offset = 0;
                pagingQueryModel1.Limit = 100;
                pagingQueryModel1.Model = new CBS_QuestionsDto();
                pagingQueryModel1.Model.DegreeOfDifficulty = dto.DegreeOfDifficulty;
                pagingQueryModel1.Model.TestQuestionsType = "单选";
                IPageModel<CBS_QuestionsDto> result1 = await _questions.GetList(pagingQueryModel1);


                PagingModel<CBS_QuestionsDto> pagingQueryModel2 = new PagingModel<CBS_QuestionsDto>();
                pagingQueryModel2.Offset = 0;
                pagingQueryModel2.Limit = 100;
                pagingQueryModel2.Model = new CBS_QuestionsDto();
                pagingQueryModel2.Model.DegreeOfDifficulty = dto.DegreeOfDifficulty;
                pagingQueryModel2.Model.TestQuestionsType = "多选";
                IPageModel<CBS_QuestionsDto> result2 = await _questions.GetList(pagingQueryModel2);


                PagingModel<CBS_QuestionsDto> pagingQueryModel3 = new PagingModel<CBS_QuestionsDto>();
                pagingQueryModel3.Offset = 0;
                pagingQueryModel3.Limit = 100;
                pagingQueryModel3.Model = new CBS_QuestionsDto();
                pagingQueryModel3.Model.DegreeOfDifficulty = dto.DegreeOfDifficulty;
                pagingQueryModel3.Model.TestQuestionsType = "判断";
                IPageModel<CBS_QuestionsDto> result3 = await _questions.GetList(pagingQueryModel3);
                if (result1.RowCount < dto.SingleNumber)
                {
                    return this.JsonFaild("题库单选题数量不足，请先添加试题，当前试题数：" + result1.RowCount.ToString());
                }
                else
                {
                    int[] SingleNumber = Tool.GetRandomArray(dto.SingleNumber.Value, 0, result1.RowCount - 1);

                    for (var i = 0; i < SingleNumber.Length; i++)
                    {
                        CBS_ExamQuestionsDetailDto item = new CBS_ExamQuestionsDetailDto();
                        item.CBSQuestionsId = result1.PageData[SingleNumber[i]].Id;
                        dto.CBS_ExamQuestionsDetail.Add(item);
                    }
                }
                if (result2.RowCount < dto.MultipleNumber)
                {
                    return this.JsonFaild("题库多选题数量不足，请先添加试题，当前试题数：" + result2.RowCount.ToString());
                }
                else
                {
                    int[] MultipleNumber = Tool.GetRandomArray(dto.MultipleNumber.Value, 0, result2.RowCount - 1);

                    for (var i = 0; i < MultipleNumber.Length; i++)
                    {
                        CBS_ExamQuestionsDetailDto item = new CBS_ExamQuestionsDetailDto();
                        item.CBSQuestionsId = result2.PageData[MultipleNumber[i]].Id;
                        dto.CBS_ExamQuestionsDetail.Add(item);
                    }
                }
                if (result3.RowCount < dto.JudgmentNumber)
                {
                    return this.JsonFaild("题库判断题数量不足，请先添加试题，当前试题数：" + result3.RowCount.ToString());
                }
                else
                {
                    int[] JudgmentNumber = Tool.GetRandomArray(dto.JudgmentNumber.Value, 0, result3.RowCount - 1);

                    for (var i = 0; i < JudgmentNumber.Length; i++)
                    {
                        CBS_ExamQuestionsDetailDto item = new CBS_ExamQuestionsDetailDto();
                        item.CBSQuestionsId = result3.PageData[JudgmentNumber[i]].Id;
                        dto.CBS_ExamQuestionsDetail.Add(item);
                    }
                }
                var dto1 = await _service.InsertAsync(dto);
                return this.JsonSuccess(dto1.Id);
            }
            else
            {
                string SysDepartmentID = await _serviceItem.GetDepartmentId(UserIdentity.Id.ToString());
                if (SysDepartmentID == null || SysDepartmentID == "") { }
                else
                {
                    dto.UpdateDept = Guid.Parse(SysDepartmentID);
                }
                await _service.UpdateAsync(dto);
                return this.JsonSuccess(string.Empty);
            }
        }

        /// <summary>
        /// DeleteMuti
        ///</summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("DeleteMuti")]
        [PermissionFilter(nameof(CBS_ExamQuestionsController) + "_" + nameof(CBS_ExamQuestionsController.DeleteMutiAsync), AuthorizationConst.DELETE)]
        public async Task<IActionResult>
            DeleteMutiAsync([FromBody]Guid[] ids)
        {

            await _service.DeleteBatchAsync(ids);
            return this.JsonSuccess();
        }


        /// <summary>
        /// 根据ID获取信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("Get")]
        public async Task<IActionResult>
            Get(Guid id)
        {
            var model = await _service.GetAsync(id);
            if (model == null) return this.JsonFaild("未找到对应数据:" + id);
            return this.JsonSuccess(model);
        }


        /// <summary>
        /// 导出
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("Export")]
        [PermissionFilter(nameof(CBS_ExamQuestionsController) + "_" + nameof(CBS_ExamQuestionsController.Export), AuthorizationConst.EXPORT)]
        public async Task<IActionResult>
            Export(PagingModel<CBS_ExamQuestionsDto>
                pagingQueryModel)
        {
            var fileName = await _service.Export(pagingQueryModel);
            if (string.IsNullOrWhiteSpace(fileName))
                return this.JsonFaild(NULL_DATA_FOR_EXCEL_EXPORT);
            return this.JsonSuccess(fileName);
        }
        #endregion


    }

    public class Tool
    {
        // Number随机数个数
        // minNum随机数下限
        // maxNum随机数上限
        public static int[] GetRandomArray(int Number, int minNum, int maxNum)
        {
            int j;
            int[] b = new int[Number];
            Random r = new Random();
            for (j = 0; j < Number; j++)
            {
                int i = r.Next(minNum, maxNum + 1);
                int num = 0;
                for (int k = 0; k < j; k++)
                {
                    if (b[k] == i)
                    {
                        num = num + 1;
                    }
                }
                if (num == 0)
                {
                    b[j] = i;
                }
                else
                {
                    j = j - 1;
                }
            }
            return b;
        }

    }
}
